package com.kmxd.ams.core.license.verify.config;

import com.kmxd.ams.core.license.verify.model.LicenseVerifyManager;
import com.kmxd.ams.license.core.utils.Base64Utils;
import com.kmxd.ams.license.core.utils.CommonUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;

/** 检查证书 1. 系统开启时加载证书 2. 定时检查证书是否发生变化并且加载证书 */
@EnableScheduling
public class CheckLicenseConfigure {

  /** 文件唯一身份标识 == 相当于人类的指纹一样 */
  private String md5 = "";

  /** 5秒检测一次，不能太快也不能太慢 */
  @Scheduled(cron = "0/5 * * * * ?")
  public void checkLicense() {
    LicenseVerifyProperties properties = new LicenseVerifyProperties();
    // 如果文件不存在就不需要校验了
    if (!checkLicenseExists()) {
      LicenseVerifyManager.simpleUninstall(properties.getVerifyParam());
      return;
    }
    String readMd5 = Base64Utils.getMd5(properties.getLicensePath());
    // 文件的MD5不相等，说明 license 变化了
    if (!readMd5.equals(md5)) {
      LicenseVerifyManager.simpleInstall(properties.getVerifyParam());
      md5 = readMd5;
    }
  }

  private boolean checkLicenseExists() {
    LicenseVerifyProperties properties = new LicenseVerifyProperties();
    if (CommonUtils.isEmpty(properties.getLicensePath())) {
      return false;
    }
    File licenseFile = new File(properties.getLicensePath());
    return licenseFile.exists();
  }
}
